/*
 * Copyright (C) 2021 Baidu, Inc. All Rights Reserved.
 */
package com.chukun.rpc.protocol.serialization;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <p>json序列化，反序列化实现<p/>
 *
 * @author chukun
 * @version 1.0
 * @since 1.0-SNAPSHOT
 */
public class JsonSerialization implements TinyRpcSerialization{

    private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = generateMapper(JsonInclude.Include.ALWAYS);
    }


    @Override
    public <T> byte[] serialize(T message) throws IOException {
        if (message == null) {
            throw new NullPointerException();
        }
        if (message instanceof String) {
            return ((String) message).getBytes();
        }
        return OBJECT_MAPPER.writeValueAsString(message).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        if (data == null) {
            throw new NullPointerException();
        }
        return OBJECT_MAPPER.readValue(Arrays.toString(data), clazz);
    }

    private static ObjectMapper generateMapper(JsonInclude.Include include) {
        ObjectMapper customMapper = new ObjectMapper();
        customMapper.setSerializationInclusion(include);
        customMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        customMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
        customMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return customMapper;
    }
}
